<?php

class ItsCustomersController extends AppController {

    var $name = 'ItsCustomers';
    var $pageTitle = 'Customer Information';
    var $viewPath = 'its/admins/customers';
    var $uses = array('Customer', 'Site', 'User', 'RunningNo', 'CustLocation', 'CustProductSite', 'Province', 'ProductSerial', 'UserCoH', 'SiteCostCenter', 'CustStockOutHead', 'SiteUser', 'CSoRR', 'CSoRH');
    var $helpers = array('Html', 'Form', 'Ajax', 'My');

    function beforeFilter() {
        parent::beforeFilter();
        // ใช้ใน Tab menus element ระบุ Secondary controller ที่กำลังถูกเลือก
        $this->set('parentNav', 'its_admins');
        $this->set('tabMenu', 'tabmenus/its/admins');
    }

    function display() {
        parent::display();
        $this->paginate['Customer']['order'] = 'Customer.id';
        $this->_paging('Customer', 'LIKE');

        // รายการ Customer ที่ User นี้รับผิดชอบ
        $customerOnHands = $this->UserCoH->listCustomerOnHand($this->Auth->user('id'));
        $this->set('customerOnHands', $customerOnHands);
    }

    function save() {
        $customer_id = null;
        if (!empty($this->data)) {
            $this->Customer->query("BEGIN");
            ;
            if (empty($this->data['Customer']['cust_no'])) { // Add Customer
                $this->data['Customer']['cust_no'] = $this->RunningNo->getNextCustNo();
            }
            $this->data['Customer']['collector_id'] = $this->Auth->user('id');
            if ($this->Customer->save($this->data)) {
                $this->Customer->query("COMMIT");
                ;
                $this->Session->setFlash("Customer no {$this->data['Customer']['cust_no']} save succesfull.", 'flash/ok');
                $customer_id = $this->Customer->id;
            } else {
                $this->Customer->query("ROLLBACK");
                $this->Session->setFlash("Customer save fail.", 'flash/fail');
                // ถ้าเป็น mode edit เก็บ id เอาไว้กรณีบันทึกข้อมูลผิด
                $customer_id = $this->data['Customer']['id'];
            }
        }
        $this->setAction('view', $customer_id);
    }

    function view($id = null) {
        if ($id != null) {
            $this->Customer->contain('Site');
            $this->data = $this->Customer->findById($id);
            $this->Customer->id = $id;
            $this->set('neighbors', $this->Customer->find('neighbors', array('fields' => array('id', 'name'))));
            $this->set('mode', 'edit');
        } else {
            $this->set('mode', 'add');
        }
        $this->set('provinces', $this->Province->find('list'));
    }

    function delete($id = null) {
        $is_success = true;
        // ถ้ายังไม่มี customer product จึงจะลบได้
        if (!$this->CustProductSite->hasAny(array('customer_id' => $id))) {
            $is_success &= $this->Customer->delete($id, true);
        } else {
            $is_success = false;
        }
        if ($is_success) { // ลบ Site ต่อด้วย
            $this->Session->setFlash("Customer and All Customer Site delete succesfull.", 'flash/ok');
            $this->setAction('display');
        } else {
            $this->Session->setFlash("Can not delete this customer.", 'flash/fail');
            $this->setAction('view', $id);
        }
    }

    function inplace_editor($field, $id) {
        parent::inplace_editor($this->Customer, $field, $id);
    }

    function display_sites($customer_id = null) {
        $this->Site->contain();
        $this->data = $this->Site->findAllByCustomerId($customer_id);
        $this->set('customer_id', $customer_id);
    }

    function view_site($customer_id, $site_id = null) {
        if (!empty($site_id)) {
            $this->data = $this->Site->findById($site_id);
            $this->set('mode', 'edit');
        } else {
            $this->data = null;
            $this->set('mode', 'add');
        }
        $this->set('provinces', $this->Province->find('list'));
        $this->set('customer_id', $customer_id);
    }

    function save_site() {
        $customer_id = $this->data['Site']['customer_id'];
//        debug($this->data);
        if (!empty($this->data)) {
            $this->Site->query("BEGIN");
            if ($this->data['mode'] == 'add') {
                $this->data['Site']['site_no'] = $this->RunningNo->getNextSiteNo($customer_id);
            }
            $this->data['Site']['collector_id'] = $this->Auth->user('id');
            if ($this->Site->save($this->data)) {
                $this->Site->query("COMMIT");
                ;
                $this->Session->setFlash("Site no {$this->data['Site']['name']} save succesfull.", 'flash/ok');
            } else {
                $this->Site->query("ROLLBACK");
                $this->Session->setFlash("Site save fail.", 'flash/fail');
                // ถ้าเป็น mode edit เก็บ id เอาไว้กรณีบันทึกข้อมูลผิด
            }
        }
        $this->setAction('display_sites', $customer_id);
    }

    function delete_site($site_id) {
        $this->layout = 'ajax';
        $is_success = false;

        $this->Site->id = $site_id;
        $customer_id = $this->Site->field('customer_id');

        // ถ้า Site นี้ ไม่มี CustProductSite อยู่จะลบได้
        if ($this->CustProductSite->hasAny(array('site_id' => $site_id)) == false) {
            $is_success = $this->Site->delete($site_id);
        }

        if ($is_success) {
            $this->Session->setFlash("Site delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this site.", 'flash/fail');
        }
        $this->setAction('display_sites', $customer_id);
    }

    /**
     * action สำหรับ display customer location
     * @param int $site_id
     */
    function display_cust_locations($site_id) {
        parent::display('CustLocation');
        $this->data['CustLocation']['site_id'] = $site_id;
        $this->paginate['CustLocation']['contain'] = array('User');
        $this->_paging('CustLocation');
        $this->set('site_id', $site_id);
    }

    function save_cust_location() {
        $site_id = $this->data['CustLocation']['site_id'];

        // เช็คว่า location name ซ้ำหรือเปล่า
        if ($this->CustLocation->hasAny(array('name' => $this->data['CustLocation']['name'], 'site_id' => $site_id))) {
            $this->CustLocation->validationErrors['name'] = 'This Lacation is already taken';
            $this->Session->setFlash("Location save fail.", 'flash/fail');
        } else {

            $this->CustLocation->query("BEGIN");
            $this->data['CustLocation']['collector_id'] = $this->Auth->user('id');

            if ($this->CustLocation->save($this->data)) {
                $this->CustLocation->query("COMMIT");
                ;
                $this->Session->setFlash("Location {$this->data['CustLocation']['name']} save succesfull.", 'flash/ok');
            } else {
                $this->CustLocation->query("ROLLBACK");
                $this->Session->setFlash("Location save fail.", 'flash/fail');
            }
        }
        $this->data = null;
        $this->setAction('display_cust_locations', $site_id);
    }

    function delete_cust_location($location_id) {
        $is_success = false;

        $this->CustLocation->id = $location_id;
        $site_id = $this->CustLocation->field('site_id');

        // ถ้า Location นี้ยังไม่เคยมี product อยุ่ลบได้
        if (!$this->ProductSerial->hasAny(array('cust_location_id' => $location_id))) {
            $is_success = $this->CustLocation->delete($location_id, true);
        }

        if ($is_success) {
            $this->Session->setFlash("Location delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this location.!", 'flash/fail');
        }
        $this->setAction('display_cust_locations', $site_id);
    }

    function cust_location_inplace_editor($field, $id) {
        parent::inplace_editor($this->CustLocation, $field, $id);
    }

    /**
     * action สำหรับ display site cost center (department)
     * @param int $site_id
     */
    function display_site_cost_center($site_id) {
        parent::display('SiteCostCenter');
        $this->data['SiteCostCenter']['site_id'] = $site_id;
        $this->paginate['SiteCostCenter']['contain'] = array('User');
        $this->_paging('SiteCostCenter');
        $this->set('site_id', $site_id);
    }

    function display_site_user($site_id) {
        $this->set('siteCostCenters', $this->SiteCostCenter->find('list', array('conditions' => array('site_id' => $site_id))));

        parent::display('SiteUser');
        $this->data['SiteUser']['site_id'] = $site_id;
        $this->paginate['SiteUser']['contain'] = array('User', 'SiteCostCenter');
        $this->_paging('SiteUser');
        $this->set('site_id', $site_id);
    }

    function save_site_cost_center() {
        $site_id = $this->data['SiteCostCenter']['site_id'];

        if (!empty($this->data)) {

            // เช็คว่า Cost Center ซ้ำหรือเปล่า
            if ($this->SiteCostCenter->hasAny(array('name' => $this->data['SiteCostCenter']['name'], 'site_id' => $site_id))) {
                $this->SiteCostCenter->validationErrors['name'] = 'This Cost Center is already taken';
                $this->Session->setFlash("Cost Center save fail.", 'flash/fail');
            } else {
                $this->SiteCostCenter->query("BEGIN");

                $this->data['SiteCostCenter']['collector_id'] = $this->Auth->user('id');
                if ($this->SiteCostCenter->save($this->data)) {
                    $this->SiteCostCenter->query("COMMIT");
                    ;
                    $this->Session->setFlash("Cost Center {$this->data['SiteCostCenter']['name']} save succesfull.", 'flash/ok');
                } else {
                    $this->SiteCostCenter->query("ROLLBACK");
                    $this->Session->setFlash("Cost center save fail.", 'flash/fail');
                }
            }
        }
        $this->data = null;
        $this->setAction('display_site_cost_center', $site_id);
    }

    function save_site_user() {
        $site_id = $this->data['SiteUser']['site_id'];
        $this->data['SiteUser']['collector_id'] = $this->Auth->user('id');

        // เช็คว่า Site User ซ้ำหรือเปล่า
        if ($this->SiteUser->hasAny(array('name' => $this->data['SiteUser']['name'], 'site_cost_center_id' => $this->data['SiteUser']['site_cost_center_id'], 'site_id' => $site_id))) {
            $this->SiteUser->validationErrors['name'] = 'This Site User is already taken';
            $this->Session->setFlash("Site User save fail.", 'flash/fail');
        } else {

            $this->SiteUser->query("BEGIN");
            if ($this->SiteUser->save($this->data)) {
                $this->SiteUser->query("COMMIT");
                ;
                $this->Session->setFlash("Site User {$this->data['SiteUser']['name']} save succesfull.", 'flash/ok');
            } else {
                $this->SiteCostCenter->query("ROLLBACK");
                $this->Session->setFlash("Site user save fail.", 'flash/fail');
            }
        }
        $this->data = null;
        $this->setAction('display_site_user', $site_id);
    }

    function site_cost_center_inplace_editor($field, $id) {
        parent::inplace_editor($this->SiteCostCenter, $field, $id);
    }

    function site_user_inplace_editor($field, $id) {
        parent::inplace_editor($this->SiteUser, $field, $id);
    }

    function delete_site_cost_center($site_cost_center_id) {
        $is_success = false;

        $this->SiteCostCenter->id = $site_cost_center_id;
        $site_id = $this->SiteCostCenter->field('site_id');

        // ถ้า CustStockOutHead ยังไม่เคยมี SiteCostCenter นี้อยุ่ลบได้
        if (!$this->CustStockOutHead->hasAny(array('site_cost_center_id' => $site_cost_center_id))) {
            $is_success = $this->SiteCostCenter->delete($site_cost_center_id, true);
        }

        if ($is_success) {
            $this->Session->setFlash("Cost Center delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this cost center.!", 'flash/fail');
        }
        $this->setAction('display_site_cost_center', $site_id);
    }

    function delete_site_user($site_cost_center_id) {
        $is_success = false;

        $this->SiteUser->id = $site_cost_center_id;
        $site_id = $this->SiteUser->field('site_id');

        // ถ้า CustStockOutHead ยังไม่เคยมี SiteCostCenter นี้อยุ่ลบได้
        if (!$this->CustStockOutHead->hasAny(array('site_cost_center_id' => $site_cost_center_id))) {
            $is_success = $this->SiteUser->delete($site_cost_center_id, true);
        }

        if ($is_success) {
            $this->Session->setFlash("Site user delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this site user.!", 'flash/fail');
        }
        $this->setAction('display_site_user', $site_id);
    }

    /**
     * action สำหรับ เหตุผลที่ในการคืนของเข้า inventory ของ Customer
     * @param int $site_id
     */
    function display_cust_stock_out_return_reasons($site_id) {
        parent::display('CSoRR');
        $this->data['CSoRR']['site_id'] = $site_id;
        $this->paginate['CSoRR']['contain'] = array('User');
        $this->_paging('CSoRR');
        $this->set('site_id', $site_id);
    }

    function save_cust_stock_out_return_reasons() {
        $site_id = $this->data['CSoRR']['site_id'];

        // เช็คว่า Site User ซ้ำหรือเปล่า
        if ($this->CSoRR->hasAny(array('title' => $this->data['CSoRR']['title'], 'site_id' => $site_id))) {
            $this->CSoRR->validationErrors['title'] = 'This Reason is already taken';
            $this->Session->setFlash("Return Reason save fail.", 'flash/fail');
        } else {
            $this->CSoRR->query("BEGIN");

            $this->Site->id = $site_id;
            $this->data['CSoRR']['customer_id'] = $this->Site->field('customer_id');
            $this->data['CSoRR']['collector_id'] = $this->Auth->user('id');
            if ($this->CSoRR->save($this->data)) {
                $this->CSoRR->query("COMMIT");
                $this->Session->setFlash("Return Reason {$this->data['CSoRR']['title']} save succesfull.", 'flash/ok');
            } else {
                $this->CSoRR->query("ROLLBACK");
                $this->Session->setFlash("Return Reason saves fail.", 'flash/fail');
            }
        }
        $this->data = null;
        $this->setAction('display_cust_stock_out_return_reasons', $site_id);
    }

    function delete_cust_stock_out_return_reasons($csorr_id) {
        $is_success = false;

        $this->CSoRR->id = $csorr_id;
        $site_id = $this->CSoRR->field('site_id');

        // ถ้า CustStockOutHead ยังไม่เคยมี CSoRR นี้อยุ่ลบได้
        if (!$this->CSoRH->hasAny(array('cust_stock_out_return_reason_id' => $csorr_id))) {
            $is_success = $this->CSoRR->delete($csorr_id, true);
        }

        if ($is_success) {
            $this->Session->setFlash("Reason delete succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Can not delete this Reason.!", 'flash/fail');
        }
        $this->setAction('display_cust_stock_out_return_reasons', $site_id);
    }

    function cust_stock_out_return_reason_inplace_editor($field, $id) {
        parent::inplace_editor($this->CSoRR, $field, $id);
    }

    function import_cust_locations($site_id) {
        // มีการ upload ไฟล์เข้ามา
        if (!empty($this->data)) {
            if (is_uploaded_file($this->data['CustLocation']['file']['tmp_name'])) {
                $is_success = true;

                // อ่านไฟล์ที่ upload เข้ามา
                $fileData = fread(fopen($this->data['CustLocation']['file']['tmp_name'], "r"),
                                $this->data['CustLocation']['file']['size']);

                // แบ่งข้อมูลที่เข้ามาแต่ละแถวด้วย REGEX
                $lines = preg_split('/\r\n/', $fileData);

                // เช็คแถวแรก header ที่เข้ามาว่าจำนวน field ตรงกับ template ล่าสุดหรือไม่?
                $HEADER = 'site_id,location_name';
                if (strcmp($lines[0], $HEADER) != 0) {
                    $this->Session->setFlash("Invalid template file!!<br /> Please download a new template file.", 'flash/fail');
                } else {
                    $errMessage = 'Import Customer Location fail. <br />';

                    $collector_id = $this->Auth->user('id');

                    // loop save ทีละ แถว
                    $count = count($lines);

                    // ignore line 1 column head
                    $data = array();
                    for ($i = 1; $i < $count; ++$i) {

                        // ถ้าไม่ใช่แถวว่างสุดท้าย
                        if (!empty($lines[$i])) {

                            $l = $this->_setCustLocation($lines[$i]);
                            $l['CustLocation']['collector_id'] = $collector_id;

                            // ถ้า Site ID ไม่ถูกต้องไม่ save
                            if (!$this->Site->hasAny(array('id' => $l['CustLocation']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Site ID"' . $l['CustLocation']['site_id'] . '" <br />';
                                $is_success = false;

                                // location name ซ้ำ
                            } elseif ($this->CustLocation->hasAny(array('site_id' => $l['CustLocation']['site_id'], 'name' => $l['CustLocation']['name']))) {
                                continue;
                            }
                            $data [] = $l;
                        }
                    }

                    if ($is_success) {
                        $is_success &= $this->CustLocation->saveAll($data, array('validate' => false));
                    }

                    if ($is_success == true) {
                        $this->Session->setFlash("Import Cust Location succesfull.", 'flash/ok');
                    } else {
                        $this->Session->setFlash($errMessage, 'flash/fail');
                    }
                }
            }
            $this->Site->id = $site_id;
            $this->redirect('view/' . $this->Site->field('customer_id'));
        } else {

            // เรียกหน้า popup ให้ browse file เข้ามา
            $this->layout = 'popup';
            $this->set('popupTitle', 'Import Customer Site Location');
            $this->set('popupWidth', 450);
            $this->set('site_id', $site_id);
        }
    }

    function _setCustLocation($lines) {
        $a = str_getcsv($lines);
        $j = 0;
        $data = array();
        $data['CustLocation']['id'] = null;
        $data['CustLocation']['site_id'] = $a[$j++];
        $data['CustLocation']['name'] = $a[$j++];
        return $data;
    }

    function template_cust_locations($site_id) {
        $this->Site->id = $site_id;
        $site_name = $this->Site->field('name');
        $this->set('site_id', $site_id);
        parent::template('vmi_cust_locations_' . $site_name . '.csv');
    }

    function import_site_cost_center($site_id) {
        // มีการ upload ไฟล์เข้ามา
        if (!empty($this->data)) {
            if (is_uploaded_file($this->data['SiteCostCenter']['file']['tmp_name'])) {
                $is_success = true;

                // อ่านไฟล์ที่ upload เข้ามา
                $fileData = fread(fopen($this->data['SiteCostCenter']['file']['tmp_name'], "r"),
                                $this->data['SiteCostCenter']['file']['size']);

                // แบ่งข้อมูลที่เข้ามาแต่ละแถวด้วย REGEX
                $lines = preg_split('/\r\n/', $fileData);

                // เช็คแถวแรก header ที่เข้ามาว่าจำนวน field ตรงกับ template ล่าสุดหรือไม่?
                $HEADER = 'site_id,cost_center_name';
                if (strcmp($lines[0], $HEADER) != 0) {
                    $this->Session->setFlash("Invalid template file!!<br /> Please download a new template file.", 'flash/fail');
                } else {
                    $errMessage = 'Import Customer Cost Center fail. <br />';

                    $collector_id = $this->Auth->user('id');

                    // loop save ทีละ แถว
                    $count = count($lines);

                    // ignore line 1 column head
                    $data = array();
                    for ($i = 1; $i < $count; ++$i) {

                        // ถ้าไม่ใช่แถวว่างสุดท้าย
                        if (!empty($lines[$i])) {

                            $l = $this->_setSiteCostCenter($lines[$i]);
                            $l['SiteCostCenter']['collector_id'] = $collector_id;

                            // ถ้า Site ID ไม่ถูกต้องไม่ save
                            if (!$this->Site->hasAny(array('id' => $l['SiteCostCenter']['site_id']))) {
                                $errMessage .= 'Line #' . ($i + 1) . ' Invalid Site ID"' . $l['SiteCostCenter']['site_id'] . '" <br />';
                                $is_success = false;

                                // location name ซ้ำ
                            } elseif ($this->SiteCostCenter->hasAny(array('site_id' => $l['SiteCostCenter']['site_id'], 'name' => $l['SiteCostCenter']['name']))) {
                                continue;
                            }
                            $data [] = $l;
                        }
                    }

                    if ($is_success) {
                        $is_success &= $this->SiteCostCenter->saveAll($data, array('validate' => false));
                    }

                    if ($is_success == true) {
                        $this->Session->setFlash("Import Cost Center succesfull.", 'flash/ok');
                    } else {
                        $this->Session->setFlash($errMessage, 'flash/fail');
                    }
                }
            }
            $this->Site->id = $site_id;
            $this->redirect('view/' . $this->Site->field('customer_id'));
        } else {
            // เรียกหน้า popup ให้ browse file เข้ามา
            $this->layout = 'popup';
            $this->set('popupTitle', 'Import Customer Cost Center');
            $this->set('popupWidth', 450);
            $this->set('site_id', $site_id);
        }
    }

    function _setSiteCostCenter($lines) {
        $a = str_getcsv($lines);
        $j = 0;
        $data = array();
        $data['SiteCostCenter']['id'] = null;
        $data['SiteCostCenter']['site_id'] = $a[$j++];
        $data['SiteCostCenter']['name'] = $a[$j++];
        return $data;
    }

    function template_site_cost_center($site_id) {
        $this->Site->id = $site_id;
        $site_name = $this->Site->field('name');
        $this->set('site_id', $site_id);
        parent::template('vmi_site_cost_center_' . $site_name . '.csv');
    }
}

?>
